from logging import Handler


class DBHandler(Handler):
    """
    自定义的handler, 配置此Handler会将日志写入数据库
    """
    LogModel = None

    def __init__(self):
        super().__init__()

    def emit(self, record):
        log = self.LogModel()
        for field in getattr(log, '_meta').fields:
            if getattr(record, field.name, None):
                setattr(log, field.name, getattr(record, field.name))
            if field.name == 'message':
                setattr(log, field.name, record.getMessage())
        log.save()


# 访问日志Handler
class AccessDBHandler(DBHandler):
    pass


# 操作日志Handler
class OperationDBHandler(DBHandler):

    def emit(self, record):
        from audit.models import OperationLog
        self.LogModel = OperationLog
        super().emit(record)
